package scorer;

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.HashMap;

import javax.swing.ImageIcon;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;

import tile.Character;
import tile.Dragon;
import tile.Tile;
import tile.Wind;
import tile.Tile.SUIT;

class TilePanel extends JPanel {
	
	private static final long serialVersionUID = 1L;
	public MyComboBox[] choosers;
	JLabel picture;
	JPanel combos;
	JCheckBox winner;
	Tile tile;
	private HashMap<Tile, BufferedImage> tiles;

	public TilePanel() {
		super(new GridLayout(3, 1));
		choosers = new MyComboBox[2];
		choosers[0] = new MyComboBox(Tile.SUIT.values(), null);
		choosers[1] = new MyComboBox(choosers[0]);
		choosers[0].link = choosers[1];
		choosers[0].addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				MyComboBox srce = (MyComboBox) e.getSource();
				ArrayList<Object> validValues = null;
				switch ((Tile.SUIT) srce.getSelectedItem()) {
				case Wind:
					validValues = Wind.getValidValues();
					break;
				case Dragon:
					validValues = Dragon.getValidValues();
					break;
				default:
					validValues = Character.getValidValues();
					break;
				}
				srce.link.removeAllItems();
				for (Object anObject : validValues) {
					srce.link.addItem(anObject);
				}
			}
		});
		picture = new JLabel();
		choosers[1].addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				SUIT s = (SUIT) ((MyComboBox) e.getSource()).link
						.getSelectedItem();
				Object value = ((MyComboBox) e.getSource())
						.getSelectedItem();
				for (Tile t : tiles.keySet()) {
					if (t.suit == s && t.value.equals(value)) {
						picture.setIcon(new ImageIcon(tiles.get(t)));
						tile = t;
						break;
					}
				}
			}
		});

		choosers[0].setSelectedIndex(0);
		
		winner = new JCheckBox("Winning tile");

		combos = new JPanel(new GridLayout(2, 1));
		combos.add(choosers[0]);
		combos.add(choosers[1]);
		this.add(picture);
		this.add(combos);
		this.add(winner);
	}

	public String getTile() {
		return tile.toString();
	}

	class MyComboBox extends JComboBox {
		private static final long serialVersionUID = 1L;
		protected MyComboBox link;

		public MyComboBox(MyComboBox l) {
			super();
			link = l;
		}

		public MyComboBox(Object[] objs, MyComboBox l) {
			super(objs);
			link = l;
		}
	}
}